<script lang="ts">
    import Loading from "../Common/Loading/Loading.svelte";
    import { useFormItemContext } from "../FormItem/FormItem.svelte";
    import { useClassList } from "../utils/useClassList";
    import { useStyle } from "../utils/useStyle";
    import type { SwitchProps } from "./Switch";

    let { checked = $bindable(), ...props }: SwitchProps = $props();
    const ctx = useFormItemContext();

    const classList = $derived(
        useClassList(props, "cm-switch", {
            [`cm-switch-${props.size}`]: props.size,
            "cm-switch-disabled": props.disabled,
            "cm-switch-checked": checked,
            "cm-switch-loading": props.loading,
            "cm-switch-round": props.round ?? true,
        })
    );

    const style = $derived(
        useStyle(props, {
            "--cm-switch-default-color": props.colors && props.colors[0],
            "--cm-switch-active-color": props.colors && props.colors[1],
        })
    );

    const labels = props.labels || [];
    const values = props.values || [true, false];

    const toggleSwitch = async () => {
        if (props.disabled) {
            return;
        }
        if (props.loading) {
            return;
        }
        let ret = true;
        if (props.onBeforeChange) {
            ret = await props.onBeforeChange(checked);
        }
        if (ret) {
            const flag = checked;
            const v = !flag ? values[0] : values[1];
            checked = v;
            props.onchange?.(v);
            ctx?.onFieldChange?.();
        }
    };
</script>

{#snippet renderIcon()}
    {#if props.icon}
        <span class="cm-switch-inner-icon">
            {#if props.icon instanceof Array}
                {#if checked}
                    {@render props.icon[1]?.()}
                {:else}
                    {@render props.icon[0]?.()}
                {/if}
            {:else}
                {@render props.icon()}
            {/if}
        </span>
    {/if}
{/snippet}

<!-- svelte-ignore a11y_click_events_have_key_events -->
<!-- svelte-ignore a11y_no_static_element_interactions -->
<div class={classList} {style} tabIndex="0" onclick={toggleSwitch}>
    <!-- 文字对齐辅助 -->
    <span style="width: 0px; font-size: 12px; visibility: hidden">A</span>
    <span class="cm-switch-inner-placeholder">
        <span><span class="cm-switch-inner-button-placeholder"></span>{labels[0]}</span>
        <span><span class="cm-switch-inner-button-placeholder"></span>{labels[1]}</span>
    </span>
    <span class="cm-switch-inner">
        {@render renderIcon()}
        <span class="cm-switch-label cm-switch-label-left">{labels[0]}</span>
        <span class="cm-switch-label cm-switch-label-right">{labels[1]}</span>
    </span>
    {#if props.loading}
        <Loading />
    {/if}
    <input name={props.name} type="hidden" value={checked ? values[0] : values[1]} />
</div>
